package tech.aistar.dao.impl;

import tech.aistar.dao.IAccDao;
import tech.aistar.util.JdbcUtil;

import java.sql.*;

/**
 * 本类用来演示:
 *
 * @author: success
 * @date: 2022/8/11 1:37 下午
 */
public class AccDaoImpl implements IAccDao {
    @Override
    public void transfer(Integer fromAccId, Integer toAccId, Double money) {
        Connection conn = null;
        PreparedStatement pst = null;

        try {
            String url = "jdbc:mysql://localhost:3306/dy?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&rewriteBatchedStatements=true";
            String username = "root";
            String password = "root";
            conn = DriverManager.getConnection(url, username, password);

            //设置它的事务为手动提交方式
            conn.setAutoCommit(false);

            String sql = "update t_acc set balance = balance - ? where id=?";
            pst = conn.prepareStatement(sql);

            //发送参数
            pst.setDouble(1,money);
            pst.setInt(2,fromAccId);
            pst.executeUpdate(); // 自动commit

            //清空一下参数
            //pst.clearParameters();

            //故意搞一个异常
            //System.out.println(10/0);

            pst.setDouble(1,-money);
            pst.setInt(2,toAccId);
            pst.executeUpdate();

            //手动提交
            conn.commit();

        } catch (Exception e) {
            e.printStackTrace();
            if(conn!=null){
                try {
                    conn.rollback();//事务的回滚操作
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }finally {
            JdbcUtil.close(conn,pst);
        }
    }
}
